<?php

namespace app\index\controller\ad;

use app\common\model\AccessLog;
use ShidianUtil\Api\Tencent\Wechat\Wechat;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use think\exception\ValidateException;
use think\Request;

/**
 *
 * Class WechatUrllink
 * @package app\index\controller\ad
 */
class WechatUrllink
{
    private Request $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取微信urllink，调整小程序的超链接
     * @return ApiResponse
     * @url /ad/wechat_urllink/save
     */
    public function save(): ApiResponse
    {
        $request = $this->request;

        $path = $request->param('path', AccessLog::PAGE_MEMBER_SOUYE);
        $query = $request->param('q', '');
        $urllink = $this->getUrllink($path, $query);

        if (is_blank($urllink)) {
            throw new ValidateException('获取微信小程序链接失败，请稍后再试');
        }

        $data = [
            'urllink' => $urllink,
        ];

        return ApiResponse::success($data);
    }

    /**
     * 获取urllink
     * @param $path
     * @param $query
     * @return string|null
     */
    private function getUrllink($path, $query): ?string
    {
        $response = $this->getWechat()
            ->miniProgram(MINIPROGRAM)
            ->urllink()
            ->generateUrllink($path, $query);

        if (!$response->isSuccess()) {
            return null;
        }

        $decodeContents = $response->getDecodeContents();

        return $decodeContents['url_link'] ?? null;
    }

    private function getWechat(): Wechat
    {
        return app(Wechat::class);
    }

}
